<template>
	<view class="container">
		<!-- 回到上方按钮 -->
		<u-toast ref="uToast"></u-toast>
		<u-back-top :scroll-top="scrollTop"></u-back-top>
		<!-- 位置和通知栏 -->
		<view class="location-bar">
			<view class="location">
				<text class="iconfont" @click="onLocationBarClick"></text>
				<!-- 根据定位状态显示相应内容 -->
				<text v-if="isLocating">定位中...</text>
				<text v-else @click="onLocationBarClick">{{ recommend }}</text>
				<text class="iconfont" @click="onLocationBarClick"></text>
			</view>
			<view class="notification">
				<text class="iconfont"></text>
			</view>
		</view>
		<!-- 搜索框 -->
		<searchBox />
		<!-- 场地类型网格 -->
		<venueTypes :venueTypes="venueTypesData" />
		<!-- 场馆列表骨架屏 -->
		<view style="margin-top: 10px;" v-if="loading &&!dataLoadError">
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
		</view>
		<!-- 附近没有场馆提示 -->
		<view v-if="dataLoadError" class="no-venue-container">
			<view class="no-venue-content">
				<text class="no-venue-title">当前位置附近没有场馆</text>
				<text class="no-venue-subtitle">我们暂时没有找到您附近的场馆信息</text>
				<view class="no-venue-action" @click="generateNearVenue">
					<text>生成附近场馆数据</text>
					<view class="arrow-icon">→</view>
				</view>
			</view>
		</view>
		<!-- 场馆列表 -->
		<venueList :venueList="venueListData.data.records" v-else-if="!loading &&!dataLoadError" />
		<!-- <venueList :venueList="venueListData.data && venueListData.data.records || []" v-if="venueListData.data && venueListData.data.records" /> -->
		<!-- 显示加载相关字样 -->
		<u-loadmore marginBottom="0" v-if="venueListData.data.records.length > 0 &&!loading &&!dataLoadError"
			:status="loadmoreStatus" />
	</view>
</template>
<script>
	import Vue from 'vue';
	import searchBoxVue from "../../components/index/search-box.vue";
	// import venueTypes from '../../components/index/venueTypes.vue';
	import venueListVue from "@/components/index/venueList.vue";
	import venueTypesVue from '@/components/index/venueTypes.vue';
	import {
		getVenueList,
		getVenueTypes
	} from '@/api/index/gymtype.js';
	import {
		data,
		onLoad
	} from 'uview-ui/libs/mixin/mixin';
	import {
		store
	} from '@/store/index.js';
	import websocketApi from "@/utils/websocket";
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";
	import request from '@/utils/request.js';
	import {
		getLocationByIP,
		reverseGeocoding
	} from '@/api/index/tencentMapApi.js';
	import {
		generateNearVenue
	} from '@/api/venueDetail/dataGenerate.js';

	//获取场馆分类数据
	export function listVenueType(keyword) {
		return request.get(`/venue/listVenueType?keyword=${keyword}`);
	}
	export default {
		components: {
			searchBox: searchBoxVue,
			venueTypes: venueTypesVue,
			venueList: venueListVue
		},
		data() {
			return {
				venueTypesData: [], //假设getVenueType()返回的数组赋值给
				locationInfo: {
					latitude: null,
					longitude: null
				},
				recommend: null,
				isLocating: false, // 新增 isLocating 状态
				venueListData: {
					data: {
						current: 0,
						size: 10,
						total: 0,
						records: []
					}
				}, // 新增场馆列表数据
				// 用来控制滚动到最上方
				scrollTop: 0,
				loading: true, //控制骨架屏显示
				page: {
					pageNum: 1,
					pageSize: 8
				},
				// 总数据条数
				total: 0,
				// 数据加载状态
				loadmoreStatus: "loadmore",
				// 用来锁定，防止多次同时进行websocket连接
				lockReconnect: false,
				// 心跳一次间隔的时间，单位毫秒
				heartbeatTime: 5000,
				dataLoadError: false // 新增数据加载错误状态
			};
		},
		// 监听用户滑动到底部
		onReachBottom() {
			this.getMoreVenueList();
			console.log('页面滚动到底部，触发分页加载');
		},
		// 在滑动过程实时获取现在的滚动条位置，并保存当前的滚动条位置
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		watch: {
			loadmoreStatus(newStatus) {
				console.log('loadmoreStatus 发生变化，新值为:', newStatus);
				if (newStatus === 'loadmore') {
					console.log('分页加载成功');
				} else if (newStatus === 'nomore') {
					console.log('分页加载无新数据');
				} else if (newStatus === 'error') {
					console.log('分页加载失败');
				}
			}
		},
		methods: {
			async getLocation() {
				this.isLocating = true; // 开始定位，设置状态为定位中

				try {
					const res = await new Promise((resolve, reject) => {
						uni.getLocation({
							type: 'wgs84',
							success: (res) => {
								resolve(res);
							},
							fail: (err) => {
								reject(err);
							}
						});
					});
					this.locationInfo = {
						latitude: res.latitude,
						longitude: res.longitude,
					};
					console.log('当前位置的纬度：', res.latitude);
					console.log('当前位置的经度：', res.longitude);

					// 调用逆地址解析函数
					try {
						const recommend = await reverseGeocoding(this, res.latitude, res.longitude);
						// 更新推荐地址
						this.recommend = recommend;
						// 存储到缓存
						const userName = uni.getStorageSync('curUser').userName;
						// console.log("userName:" + JSON.stringify(userName));
						const cacheKey = `location_${userName}`;
						
						let location = {
							latitude: res.latitude,
							longitude: res.longitude,
							recommend: recommend
						};
						console.log("location:" + JSON.stringify(location));
						uni.setStorageSync(cacheKey, location);
						
						console.log("逆地址解析成功，缓存键:", cacheKey);
					} catch (error) {
						console.error('逆地址解析失败:', error);
						uni.showToast({
							title: '逆地址解析失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('获取位置失败，尝试通过 IP 获取', err);
					try {
						const location = await getLocation();
						if (location) {
							this.locationInfo = {
								latitude: location.lat,
								longitude: location.lng
							};
							console.log('通过 IP 获取的位置 - 纬度：', location.lat);
							console.log('通过 IP 获取的位置 - 经度：', location.lng);
						} else {
							uni.showToast({
								title: '通过 IP 获取位置失败',
								icon: 'none'
							});
						}
					} catch (ipErr) {
						console.error('通过 IP 获取位置失败', ipErr);
						// uni.showToast({
						// 	title: '获取位置失败',
						// 	icon: 'none'
						// });
					}
				} finally {
					this.isLocating = false; // 定位结束，无论成功与否，都设置状态为定位结束
				}
			},
			async onLocationBarClick() {
				// 清空缓存
				const userName = uni.getStorageSync('curUser').userName;
				const cacheKey = `location_${userName}`;
				uni.removeStorageSync(cacheKey);
				console.log('缓存已清空');
				// 调用 getLocation 方法
				await this.getLocation();
				// 重新获取场馆列表
				await this.getVenueListData();
			},
			clearResult() {
				this.venueListData.data.records = [];
				this.page.pageNum = 1;
				this.loadmoreStatus = "loadmore";
				this.loading = true;
				this.dataLoadError = false; // 清空结果时重置错误状态
			},
			/**
			 * 发起场馆列表请求
			 */
			async fetchVenueList() {
				try {
					return await getVenueList({
						current: this.page.pageNum - 1,
						size: this.page.pageSize,
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude,
						km: 10,
					});
					if (!response.data || !response.data.records || response.data.records.length === 0) {
						console.error('获取场馆列表数据为空');
						this.dataLoadError = true;
						this.loading = false;
						throw new Error('获取场馆列表数据为空');
					}
					return response;
				} catch (error) {
					console.error('获取场馆列表数据失败:', error);
					this.loading = false; // 隐藏骨架屏
					throw error;
				}
			},
			async generateNearVenue() {
				const res = await generateNearVenue({
					latitude: this.locationInfo.latitude,
					longitude: this.locationInfo.longitude
				});
				if (res.success) {
					this.$refs.uToast.show({
						type: 'success',
						message: "请求发送成功，请稍等 10 秒之后刷新页面"
					})
				}
			},
			async getVenueListData() {
				try {
					console.log('传递的经纬度:', {
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude
					});
					const venueListRes = await getVenueList({
						// venueListReqDTO: {
						current: 0,
						// size: 10,
						// 修改为 page.pageSize
						size: this.page.pageSize,
						// name: '',
						// type: null,
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude,
						km: 10,
						// status: null
						// }
					});
					// const venueListRes = await getVenueList({
					// 	// venueListReqDTO: {
					// 		current: 0,
					// 		size: 10,
					// 		// name: '',
					// 		// type: null,
					// 		latitude: 34.131,
					// 		longitude: 108.8,
					// 		km: 10,
					// 		// status: null
					// 	// }
					// });
					// console.log('场馆查询数据:', JSON.stringify(venueListRes));
					if (!venueListRes.data || !venueListRes.data.records || venueListRes.data.records.length === 0) {
						console.error('获取场馆列表数据为空');
						this.dataLoadError = true;
						this.loading = false;
						return;
					}
					this.venueListData.data.records = venueListRes.data.records;
					this.total = venueListRes.data.total;
					// console.log('场馆列表数据:',JSON.stringify(this.venueListData.records));
					// this.venueListData.records = venueListRes.data.records;
				} catch (error) {
					console.error('获取场馆列表数据失败:', error);
					this.loading = false; // 隐藏骨架屏
				}
			},

			/**
			 * 获取下一页的场馆信息
			 */
			async getMoreVenueList() {
				if (this.venueListData.data.records.length >= this.total) {
					// 没有更多数据了
					this.loadmoreStatus = "nomore";
				} else {
					if (!this.loading) {
						this.page.pageNum++;
						// 显示正在加载
						this.loadmoreStatus = "loading";
						// 修改后
						try {
							const newData = await this.fetchVenueList();
							this.venueListData.data.records = this.venueListData.data.records.concat(newData.data
								.records);
							this.loadmoreStatus = newData.data.records.length > 0 ? "loadmore" : "nomore";
						} catch (error) {
							console.error('获取下一页场馆列表数据失败:', error);
							this.loadmoreStatus = "error";
							this.loading = false; // 隐藏骨架屏
							this.loadmoreStatus = "error";
						}
					}
				}
			},
		},
		onLoad() {
			// 获取用户名缓存
			const userName = uni.getStorageSync('curUser').userName;
			// 拼接缓存键
			const cacheKey = `location_${userName}`;
			// 检查缓存中是否有推荐地址
			let cachedAddress = uni.getStorageSync(cacheKey);
			if (cachedAddress) {
				this.getRecommend = cachedAddress.recommend;
			} else {
				// 缓存中没有数据，让用户定位
				this.getLocation();
			}
		},
		async created() {
			try {
				// 发起请求获取场地类型和场馆列表数据
				// const [venueTypesRes] = await Promise.all([getVenueTypes()]);
				const res = await getVenueTypes();
				console.log('完整响应数据:', JSON.stringify(res.data)); // 确认数据结构
				this.venueTypesData = res.data;
				// await getLocationByIP(this);
				await this.getLocation();
				// const venueListRes = await getVenueList();
				await this.getVenueListData();
				// console.log('场馆查询数据:',JSON.stringify(venueListRes.data));
				// 假设场馆列表数据直接是一个数组
				// this.venueListData = venueListRes.data;
				// alert(JSON.stringify(this.venueListData.data.records, null, 2));
			} catch (error) {
				console.error('获取数据失败:', error);
			} finally {
				this.loading = false; // 数据加载完成，隐藏骨架屏
			}
		}
	}
	// export default {
	//     data() {
	//         return {
	//             sportsVenues: [],
	//             activityRooms: [],
	//             functionRooms: [],
	//             venues: []
	//         };
	//     },
	//     created() {
	//         this.$webSocketService.initWebsocket(this.$store, this.Constant);
	//         this.fetchVenueTypes();
	//         this.fetchVenueList();
	//     },
	//     methods: {
	//         async fetchVenueTypes() {
	//             try {
	//                 const res = await getVenueTypes();
	//                 // 假设 res.data 包含了场地类型数据，这里需要根据实际接口返回格式调整
	//                 // 同时需要根据实际数据结构将数据分配到 sportsVenues、activityRooms、functionRooms 中
	//                 console.log('场地类型数据:', res);
	//             } catch (error) {
	//                 console.error('获取场地类型数据失败:', error);
	//             }
	//         },
	//         async fetchVenueList() {
	//             try {
	//                 const res = await getVenueList();
	//                 // 假设 res.data 包含了场馆列表数据，这里需要根据实际接口返回格式调整
	//                 this.venues = res.data;
	//                 console.log('场馆列表数据:', res);
	//             } catch (error) {
	//                 console.error('获取场馆列表数据失败:', error);
	//             }
	//         }
	//     }
	// }
</script>

<style lang="scss">
	@import '@/static/icon/iconfont.css';

	.container {
		min-height: 100vh;
		background-color: #f8f9fa;
		background-size: 100%;
		padding-bottom: 20px;

		.location-bar {
			background: linear-gradient(135deg, #52a3fe 0%, #3d89e5 100%);
			padding: 12px 16px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: white;
			box-shadow: 0 2px 8px rgba(74, 144, 226, 0.2);

			.location {
				display: flex;
				align-items: center;
				gap: 6px;
				font-size: 15px;
				font-weight: 500;

				.iconfont {
					font-size: 18px;
					opacity: 0.9;
					transition: opacity 0.2s;

					&:active {
						opacity: 0.7;
					}
				}
			}

			.notification {
				.iconfont {
					font-size: 20px;
					opacity: 0.9;
					transition: opacity 0.2s;

					&:active {
						opacity: 0.7;
					}
				}
			}
		}

		.skeleton-screen {
			background-color: #fff;
			border-radius: 12px;
			padding: 16px;
			// margin: 8px 16px;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
		}

		.full-screen {
			position: relative;
			width: calc(100% - 32px);
			height: auto;
			min-height: 100px;
			z-index: 99;
		}

		/* 没有场馆提示样式 */
		.no-venue-tip {
			text-align: center;
			padding: 30px 20px;
			color: #6c757d;
			font-size: 15px;
			background-color: #fff;
			border-radius: 12px;
			margin: 16px;
			box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
		}
	}

	.no-venue-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 300px;
		background: linear-gradient(135deg, #ffffff 0%, #eff3f7 100%);
		border-radius: 12px;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
		margin: 20px;
		padding: 30px;
	}

	.no-venue-content {
		text-align: center;
		max-width: 400px;
	}

	.no-venue-title {
		display: block;
		font-size: 18px;
		font-weight: 600;
		color: #2c3e50;
		margin-bottom: 8px;
		letter-spacing: 0.5px;
	}

	.no-venue-subtitle {
		display: block;
		font-size: 14px;
		color: #7f8c8d;
		margin-bottom: 24px;
		line-height: 1.5;
	}

	.no-venue-action {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(to right, #3498db, #2980b9);
		color: white;
		padding: 12px 24px;
		border-radius: 30px;
		font-size: 15px;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.3s ease;
		box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
	}

	.no-venue-action:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(52, 152, 219, 0.4);
	}

	.no-venue-action:active {
		transform: translateY(0);
	}

	.arrow-icon {
		margin-left: 8px;
		font-weight: bold;
		transition: transform 0.3s ease;
	}

	.no-venue-action:hover .arrow-icon {
		transform: translateX(3px);
	}
</style>